package edu.scau.mis.pos.service.impl;

import edu.scau.mis.pos.domain.Change;
import edu.scau.mis.pos.domain.OrderItem;
import edu.scau.mis.pos.mapper.ChangeMapper;
import edu.scau.mis.pos.mapper.OrderItemMapper;
import edu.scau.mis.pos.mapper.ProductMapper;  // 假设你有这个Mapper来处理库存和销量
import edu.scau.mis.pos.service.IChangeService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ChangeServiceImpl implements IChangeService {

    @Resource
    private ChangeMapper changeMapper;

    @Resource
    private ProductMapper productMapper;  // 用于更新库存和销量

    @Resource
    private OrderItemMapper orderItemMapper;  // 用于获取订单明细

    // 查询所有换货记录
    @Override
    public List<Change> listChanges(String changeSn, String orderId, Integer status, String startTime, String endTime, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        return changeMapper.selectChangeList(changeSn, orderId, status, startTime, endTime, offset, pageSize);
    }

    // 确认换货
    @Override
    public boolean confirmChange(String changeSn, String orderId) {
        // 1️⃣ 获取换货记录
        Change change = changeMapper.selectChangeBySn(changeSn);

        // 2️⃣ 获取订单明细
        List<OrderItem> orderItems = orderItemMapper.selectOrderItemsByOrderId(orderId);

        // 3️⃣ 遍历订单明细，恢复库存并更新销量
        for (OrderItem item : orderItems) {
            productMapper.increaseStockQuantity(item.getSkuCode(), item.getQuantity());  // SKU库存
            productMapper.decreaseSalesAndIncreaseStock(item.getProductSn(), item.getQuantity()); // 商品销量减少 + 商品库存增加
        }

        // 4️⃣ 更新换货表，标记为已确认换货
        int rows1 = changeMapper.updateChangeStatus(changeSn, 4);  // 状态4表示换货完成

        // 5️⃣ 更新订单状态为换货完成
        int rows2 = changeMapper.updateOrderStatus(orderId, 4);  // 假设状态4表示换货完成

        return rows1 > 0 && rows2 > 0;
    }

    // 删除换货记录
    @Override
    public boolean deleteChange(String changeSn) {
        int rows = changeMapper.deleteChangeBySn(changeSn);
        return rows > 0;
    }

    // 根据订单ID查询订单明细
    @Override
    public List<OrderItem> getOrderDetailsByOrderId(String orderId) {
        return changeMapper.selectOrderDetailsByOrderId(orderId);
    }

    // 获取所有换货记录
    @Override
    public List<Change> listAllChanges(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        return changeMapper.selectAllChanges(offset, pageSize);
    }

    // 根据换货单号获取换货记录
    @Override
    public Change getChangeBySn(String changeSn) {
        return changeMapper.selectChangeBySn(changeSn);
    }

    @Override
    public int updateChange(Change change) {
        return changeMapper.updateChange(change);
    }

}
